/*
 Play a melody
*/

#include "pitches.h"

// 记录曲子的音符
int melody[] = { 0, 0, NOTE_E5, NOTE_D5, NOTE_E5, NOTE_D5, NOTE_E5, NOTE_B4, NOTE_D5, NOTE_C5, 
                 NOTE_A4, 0, NOTE_C4, NOTE_E4, NOTE_A4, NOTE_B4, 0, NOTE_E4, NOTE_G4, NOTE_B4, 
                 NOTE_C5, 0, NOTE_E4, NOTE_E5, NOTE_D5, NOTE_E5, NOTE_D5, NOTE_E5, NOTE_B4, NOTE_D5, NOTE_C5,
                 NOTE_A4, 0, NOTE_C4, NOTE_E4, NOTE_A4, NOTE_B4, 0, NOTE_E4, NOTE_C5, NOTE_B4,
                 NOTE_A4
               };

// 音符持续时间：4为四分音符，8为八分音符
int noteDurations[] = { 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 
                        4, 8, 8, 8, 8, 4, 8, 8, 8, 8, 
                        4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 
                        4, 8, 8, 8, 8, 4, 8, 8, 8, 8,
                        4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 
                        4
                      };

void setup() {

  // 遍历整个曲子的音符
  for(int thisNote = 0; thisNote < sizeof(melody)/sizeof(melody[0]); thisNote++) {

    // 需要根据音符类型换算音符的持续时间
    int noteDuration = 1000/noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // 为了能辨别出不同的音调，需要在两个音调间设置一定的延时，增加30%比较合适
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    noTone(8);
  }
  
}

void loop() {
  
}
